<template>
  <div class="purchase-order">
      <div slot="header" class="clearfix" style="text-align: center">
        <h1>采购申请单</h1>
      </div>
    <div style="margin-bottom: 20px;">
      <el-row>
        <el-col :span="12">
          <el-button type="primary" icon="el-icon-plus" @click="openGoodsListDialog">添加商品</el-button>
          <el-button type="danger" icon="el-icon-delete" >删除商品</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button type="primary" @click="confirmReceipt" class="el-icon-check"> 提交申请</el-button>
          <el-button @click="cancel" class="el-icon-refresh"> 重置数据</el-button>
        </el-col>
      </el-row>
    </div>
    <div>
      <el-form label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号:">
              {{ orderInfo.purchaseOrderNumber }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="登记人:">
              <el-input placeholder="请输入登记人" style="width: 200px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登记时间:">
              {{ orderInfo.registerTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总数量:"> <!-- 新增: 总数量显示 -->
              {{ totalQuantity }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总计:">
              {{ totalAmount }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table :data="orderItems" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="image" label="图`片" width="80" align="center">
        <template slot-scope="scope">
          <img :src="'/img'+scope.row.image" alt="商品图片" style="width: 40px; height: 40px;">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="200" align="center"></el-table-column>
      <el-table-column prop="companyName" label="供应商公司名称（联系电话）" width="240" align="center"></el-table-column>
      <el-table-column prop="price" label="单价(元)" width="150" align="center"></el-table-column>
      <el-table-column prop="unit" label="商品单位" width="200" align="center"></el-table-column>
      <el-table-column prop="count" label="数量(件)" width="200" align="center">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.count" :min="0" max="1000"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="小计（元）" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.price * scope.row.count }}
        </template>
      </el-table-column>
    </el-table>


    <!-- 新增商品列表弹窗 -->
    <el-dialog title="商品列表" :visible.sync="goodsListDialogVisible" width="80%" top="5vh">
      <div class="goods-list-dialog">
        <el-form inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="一级分类">
            <el-select v-model="searchForm.firstCategory" placeholder="请选择类型">
              <el-option v-for="level in firstCategoryList" :key="level.typeId" :label="level.typeName" :value="level.typeId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类">
            <el-select v-model="searchForm.secondCategory" placeholder="请选择类型">
              <el-option v-for="level in secondCategoryList" :key="level.typeId" :label="level.typeName" :value="level.typeId"></el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form>

        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="productId" label="编号" width="80" align="center"></el-table-column>
          <el-table-column prop="imgLink" label="图片" width="80" align="center">
            <template slot-scope="scope">
              <img :src="'/img'+scope.row.imgLink" alt="Icon" style="width: 40px; height: 40px;">
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="showDetail(scope.row)">{{ scope.row.name }} <i class="el-icon-view"></i></el-button>
            </template>
          </el-table-column>
          <el-table-column prop="typeId" label="商品类型" align="center"></el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="showSupplierGoodsDetails(scope.row.productId)" class="el-icon-sell"> 查看供应商</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-sizes="[5,10,15,20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 20px; text-align: right;"
        ></el-pagination>
      </div>
    </el-dialog>

    <!-- 新增供应商商品详情弹窗 -->
    <el-dialog title="供应商商品" :visible.sync="supplierGoodsDialogVisible" width="60%" height="700px" top="5vh">
      <div class="supplier-goods-dialog">
        <el-form inline>
          <el-form-item label="供应商公司名称" >
            <el-input v-model="searchForm2.supplierName" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-button type="primary" @click="onSearchSupplier">查询</el-button>
          <el-button @click="onResetSupplier">重置</el-button>
        </el-form>

        <el-table :data="supplierGoodsTableData" style="width: 100%;height: 500px">
          <el-table-column prop="id" label="编号" width="50" align="center"></el-table-column>
          <el-table-column prop="imgLink" label="图片" width="80" align="center">
            <template slot-scope="scope">
              <img :src="'/img'+scope.row.imgLink" alt="商品图片" style="width: 40px; height: 40px;">
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" width="150" align="center"></el-table-column>
          <el-table-column prop="companyName" label="供应商公司名称(联系电话)" width="250" align="center"></el-table-column>
          <el-table-column prop="price" label="单价(元)" width="100" align="center"></el-table-column>
          <el-table-column prop="unit" label="商品单位" width="100" align="center"></el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="onAddStock(scope.$index, scope.row)" class="el-icon-check">  添加采购</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
            @size-change="handleSizeChangeSupplier"
            @current-change="handleCurrentChangeSupplier"
            :current-page.sync="currentPageSupplier"
            :page-sizes="[5,10,15,20]"
            :page-size="pageSizeSupplier"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSupplier"
            style="margin-top: 20px; text-align: right;"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'; // 新增: 引入 mapState 辅助函数

export default {
  name: "PurchaseOrder",
  data() {
    return {
      Data: [
        {
          productId:'苹果',
          checkReason: "",
          checkTag: "S001-1",
          checkTime: "2023-10-01T12:00:00Z",
          checker: "",
          conveyTag: "P001-1",
          gatherTag: "K001-1",
          payMethod: "",
          purchaseId: null,
          purchaseOrderNumber: "",
          sppelierItems:[
            {supplierId:'1',price:'6',count:'12'},
            {supplierId:'2',price:'5',count:'15'}
          ],
        },
        {
          productId:'香蕉',
          checkReason: "",
          checkTag: "S001-1",
          checkTime: "2023-10-01T12:00:00Z",
          checker: "",
          conveyTag: "P001-1",
          gatherTag: "K001-1",
          payMethod: "",
          purchaseId: null,
          purchaseOrderNumber: "",
          sppelierItems:[
            {supplierId:'1',price:'10',count:'20'},
            {supplierId:'2',price:'12',count:'10'}
          ],
        }
      ],
      searchForm: {
        productName: "",
        firstCategory: "",
        secondCategory: ""
      },
      currentPage: 1,
      pageSize: 5,
      total: 0,
      firstCategoryList: {},
      secondCategoryList: {},
      tableData: [],
      supplierGoodsDialogVisible: false,
      searchForm2: {
        supplierName: "",
      },
      currentPageSupplier: 1,
      pageSizeSupplier: 5,
      totalSupplier: 0,
      supplierGoodsTableData: [
        {
          id: "",
          imgLink: "",
          name: "",
          companyName: "",
          price: "",
          unit: "",
          supplierId: "",
          productId: ""
        },
      ],
      orderInfo: {
        purchaseOrderNumber: '',
        register: '',
        registerTime: '' // 修改: 初始化为空字符串
      },
      orderItems: [],
      goodsListDialogVisible: false,
      totalQuantity: 0, // 新增: 总数量变量
    };
  },
  computed: {
    ...mapState(['user']), // 新增: 映射 store 中的 user 状态
    totalAmount() {
      return this.orderItems.reduce((total, item) => total + (item.price * item.count), 0);
    }
  },
  methods: {
    //提交申请
    confirmReceipt() {
      // 确认收货入库逻辑
      console.log('确认收货入库');
      this.$confirm('确认提交申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认提交申请逻辑
        console.log('确认提交申请');
        this.$axios.post('http://localhost:8090/purchase-order/addPurchaseOrder', this.orderItems).then(data => {
            console.log('data:', data);
            if (data) {
              this.$message({
                type: 'success',
                message: '提交申请成功！需要审核'
              });
              this.orderItems = [];
            } else {
              this.$message({
                type: 'error',
                message: '提交申请失败！'
              });
            }
          })
      })
    },
    cancel() {
      // 取消操作逻辑
      console.log('取消');
    },
    openGoodsListDialog() {
      this.initProduct();
      this.goodsListDialogVisible = true;
    },
    onSearch() {
      console.log('搜索:', this.searchForm);
      this.initProduct();
    },
    onReset() {
      this.searchForm = {
        productName: "",
        firstCategory: "",
        secondCategory: ""
      };
    },
    showDetail() {
      console.log('查看详情');
    },
    //添加采购库存按钮
    onAddStock(index, row) {
      // 检查 orderItems 是否已包含相同商品
      const isExist = this.orderItems.some(item => item.name === row.name);
      if (isExist) {
        // 显示不能重复添加的提示信息
        this.$message({
          type: 'warning',
          message: '不能重复添加'
        });
        return;
      }
      // 将供应商商品信息添加到 orderItems 中
      const newItem = {
        index: this.orderItems.length + 1,
        image: row.imgLink,
        name: row.name,
        companyName: row.companyName,
        price: row.price,
        unit: row.unit,
        count: 1, // 默认数量为1，可以根据实际需求调整
        subtotal: row.price * 1, // 计算小计
        supplierId: row.supplierId,
        productId: row.productId
      };
      this.orderItems.push(newItem);
      console.log('供应商id'+row.supplierId);
      console.log('商品id'+row.productId);
      // 判断 orderItems 是否有值并提示信息
      if (this.orderItems.length > 0) {
        this.$message({
          type: 'success',
          message: '添加商品采购成功！'
        });
      }
    },
    //新增商品分页
    handleSizeChange() {
      this.initProduct();
    },
    handleCurrentChange() {
      this.initProduct();
    },
    initProduct() {
      Object.assign(this.searchForm, {"currentPage": this.currentPage, "pageSize": this.pageSize})
      this.$axios.post("http://localhost:8090/product/getAllProduct", this.searchForm).then(({ data }) => {
        console.log(data);
        this.tableData = data.records;
        this.total = data.total;
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化失败!'
        });
      })
    },
    onSearchSupplier() {
      console.log('搜索供应商:', this.searchForm);
      this.initSupplierProduct(this.searchForm2);
    },
    onResetSupplier() {
      this.searchForm2 = {
        supplierName: ""
      };
    },
    handleSizeChangeSupplier() {
      this.initSupplierProduct(this.searchForm2);
    },
    handleCurrentChangeSupplier() {
      this.initSupplierProduct(this.searchForm2);
    },
    //点击查看供应商，初始化供应商商品列表
    showSupplierGoodsDetails(productId) {
      console.log('查看供应商详情'+productId);
      this.supplierGoodsDialogVisible = true;
      this.initSupplierProduct(productId);
    },
    //根据商品id查询该商品的所有供应商
    initSupplierProduct(productId) {
      Object.assign(this.searchForm, {"currentPage": this.currentPageSupplier, "pageSize": this.pageSizeSupplier, "productId": productId})
      this.$axios.post("http://localhost:8090/supplier-product/getSupplierProductServiceByProductId", this.searchForm).then(({ data }) => {
        console.log(data);
        this.supplierGoodsTableData = data.records.map(record => ({
            id: record.id,
            price: record.price,
            name: record.product.name,
            imgLink: record.product.imgLink,
            companyName: record.supplier.companyName +"("+record.supplier.phone+")",
            unit: record.product.unit,
            supplierId: record.supplierId,
            productId: record.productId
        }));
        this.totalSupplier = data.total;
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化失败!'
        });
      })
    },
    handleSelectionChange(val) {
      this.selectedProducts = val.map(item => item.productId);
    },
    updateRegisterTime() { // 新增: 更新登记时间的方法
      this.orderInfo.registerTime = new Date().toLocaleString();
    },
    calculateTotalQuantity() { // 新增: 计算总数量的方法
      this.totalQuantity = this.orderItems.reduce((total, item) => total + item.count, 0);
    },
    //初始化一级分类
    initFirstLevel() {
      this.$axios.get("http://localhost:8090/product-type/getProductTypeFirstLevel").then(({ data }) => {
        console.log(data);
        this.firstCategoryList = data;
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化一级分类失败!'
        });
      })
    },
    //初始化二级分类
    initSecondtLevel() {
      this.$axios.get("http://localhost:8090/product-type/getProductTypeSecondLevel").then(({ data }) => {
        console.log(data);
        this.secondCategoryList = data;
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化二级分类失败!'
        });
      })
    },
  },
  watch: {
    orderItems: {
      handler() {
        this.calculateTotalQuantity(); // 监听 orderItems 变化时调用计算总数量的方法
      },
      deep: true
    }
  },
  mounted() {
    this.updateRegisterTime(); // 新增: 组件挂载时更新登记时间
    this.initFirstLevel();
    this.initSecondtLevel();
  }
};
</script>

<style scoped>
.purchase-order {
  margin: 20px;
}
.el-table .cell {
  text-align: center;
}
.el-table >>> .el-table__header tr th {
  background-color: lightgray;
  color: black;
}
.goods-list-dialog {
  padding: 20px;
}

/* 确保表格和其他元素在弹窗内居中显示 */
.el-dialog .el-table {
  margin: 0 auto;
}
/* 确保表格和其他元素在弹窗内居中显示 */
.el-dialog .el-table {
  margin: 0 auto;
}
.supplier-goods-dialog {
  padding: 20px;
}
.el-main[data-v-2b833318] {
  background-color: white;
  color: black;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
  margin: 10px;
  border-radius: 5px;
}
</style>
